package com.secneo.appshare.threads;

import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.secneo.appshare.activities.MainLogsActivity;
import com.secneo.appshare.api.RemoteApi.LatestActivity;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.common.Util;

public class ActivityThread extends Thread
{
	private final static String TAG = "MyTag";
	private Handler handler;
	private Context ctx;
	private int number;
	private String uid;
	private List<LatestActivity> mActivityList;

	private boolean running = true;
	private String time="";

	public ActivityThread(Context ctx, Handler handler, String uid, int number,String time)
	{
		this.handler = handler;
		this.ctx = ctx;
		this.number = number;
		this.uid = uid;
		this.time=time;
	}

	public synchronized void stopRun(){
		running = false;
		this.interrupt();

	}
	
	public List<LatestActivity> getActivitys()
	{
		return mActivityList;
	}

	public void run() 
	{
		try 
		{
			running = true;
			RemoteApiImpl remoteApi = new RemoteApiImpl();
			mActivityList = remoteApi.getLatestActivity(ctx, uid, number, time);
			if (mActivityList == null) 
			{
				Message msg = new Message();
				msg.what = Constants.MSG_GET_RECOMS_NETWORK_ERROR;
				handler.sendMessage(msg);
				return;
			}
			
			if (!running) 
				return;
			Message msg = new Message();
			msg.what = Constants.MSG_GET_ACTIVITY_FINISH;
			handler.sendMessage(msg);
			
			for(int i = 0; i < mActivityList.size(); i++) 
			{
				if (!running) 
				{
					Log.d(TAG, "ActivityThread is stoped......");
					return;
				}
				LatestActivity act =  mActivityList.get(i);
				String appUrl = Constants.SERVER_ICON_URL + act.app_icon;
				Drawable dw = Util.getDrawableFromCache(ctx, appUrl);
				if (dw != null)
				{
					act.app_icon_drawable = dw;
				}
				
				try
				{
					String userUrl = act.user_icon;
					if(userUrl.contains("buildin"))
						act.user_icon_drawable = Util.getDrawableFromAsset(ctx, userUrl);
					else
						act.user_icon_drawable = Util.getDrawableFromCache(ctx, userUrl);
					
				}catch(Exception ex) {
					Log.d(TAG, "ActivityThread::Run() read icon error = "+ex.getMessage());
				}

				if((act.app_icon_drawable != null)||(act.user_icon_drawable != null))
				{
					Message iconmsg = new Message();
					iconmsg.what = Constants.MSG_GET_ACTIVITYICON_FINISH;
					handler.sendMessage(iconmsg);
				}
			}
			MainLogsActivity.setAllowGetPageAgain();
			
		} catch(Exception ex) {
			Log.d(TAG, "ActivityThread::Run() error = "+ex.getMessage());
			Message msg = new Message();
			msg.what = Constants.MSG_GET_RECOMS_NETWORK_ERROR;
			handler.sendMessage(msg);
		}
	}
}
